<template>
  <div class="search-container">
    <div class="page-nav-bar">
      <form>
        <van-search
          v-model="searchValue"
          show-action
          placeholder="请输入搜索关键词"
          @search="onSearch"
          @cancel="onCancel"
        ></van-search>
      </form>
    </div>
    <!-- 历史记录 联想建议 搜索结果 -->
    <result-search v-if="isResultShow" :search-value="searchValue"></result-search>
    <suggestion-search v-else-if="searchValue" :search-value="searchValue" @get-suggestion-value="getSuggestionValue($event)"></suggestion-search>
    <history-search v-else></history-search>

  </div>
</template>

<script>
import HistorySearch from './history-search.vue'
import SuggestionSearch from './suggestion-search.vue'
import ResultSearch from './result-search.vue'
import { setToken, getToken } from '@/utils/storage.js'
export default {
  name: 'SearchIndex',
  components: {
    HistorySearch,
    SuggestionSearch,
    ResultSearch
  },
  data() {
    return {
      searchValue: null,
      isResultShow: false,
      historyList: []
    }
  },
  methods: {
    async onSearch(value) {
      this.historyList = getToken('HISTORY-LIST')
      this.isResultShow = true
      if (this.historyList.indexOf(value) !== -1) {
        this.historyList.splice(this.historyList.indexOf(value), 1)
      }
      this.historyList.unshift(value)
      setToken('HISTORY-LIST', this.historyList)
    },
    onCancel() {
        this.$router.back()
    },
    getSuggestionValue(value) {
        this.searchValue = value
        this.onSearch()
    }
  }
}
</script>

<style scope lang="less">
.search-container {
    .page-nav-bar {
        position: sticky;
        top: 0;
        left: 0;
        z-index: 10;
        .van-search {
            background-color: rgba(0, 0, 0, 0);
            .van-search__content {
                border-radius: 6px;
                background-color: #f4f5f6;
            }
            i.van-icon-search {
                font-size: 30px;
            }
            .van-search__action {
                color: #fff;
                font-size: 32px;
                margin-left: 24px;
            }
        }
        .van-search--show-action {
            padding: 20px 32px
        }
    }

}
</style>
